package com.xiaodu.dynamicdatasource.aop;

import com.xiaodu.dynamicdatasource.anno.SelectDB;
import com.xiaodu.dynamicdatasource.config.DataSourceContextHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author: dutianjie
 * @date: 2021/4/22
 * @version: v1.0.0
 * @description: 描述
 **/
@Aspect
@Component
public class DynamicDatasouceAop {


    @Pointcut("execution(* com.xiaodu.dynamicdatasource.mapper.*.*(..))")
    public void point() {
    }

    @Around(value = "point()")
    public Object dbSelect(ProceedingJoinPoint joinpoint) throws Throwable {
        Object proceed = null;
        try {
            MethodSignature signature = (MethodSignature) joinpoint.getSignature();
            Method method = signature.getMethod();
            SelectDB selectDB = method.getAnnotation(SelectDB.class);
            if (selectDB != null) {
                String value = selectDB.value();
                if (DataSourceContextHolder.validateDataSourceKey(value)) {
                    DataSourceContextHolder.setDataSourceKey(value);
                } else {
                    throw new RuntimeException("datasource key not fond");
                }

            }
            proceed = joinpoint.proceed();

        } finally {
            DataSourceContextHolder.removeDataSourceKey();
        }
        return proceed;

    }
}
